/**
 * 
 */
package fb.chatter.utils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.io.IOUtils;

import fb.chatter.constant.Constant;

/**
 * @author hoannguyen
 *
 */
public final class AccessTokenUtils {

	/**
	 * To get access token value from the given codeUrl
	 * 
	 * @param codeUrl
	 * @return
	 */
	public static String getAccessTokenValue(String codeUrl) {

		String accessToken = null;
		try {
			
			// Build AccessToken URL.
			String accessTokenUrl = buildAccessTokenUrlWithCodeUrl(codeUrl);
			
			// Send a GET request to facebook server.
			URL url = new URL(accessTokenUrl);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			connection.setDoOutput(true);
			connection.connect();

			// Get access token value.
			InputStream is = connection.getInputStream();
			String responseContent = IOUtils.toString(is, "UTF-8");
			accessToken = parseAccessTokenResponse(responseContent);
			
			System.out.println(accessToken);
			is.close();
			connection.disconnect();

		} catch (IOException e) {
			ExceptionUtils.log(e);
		}
		return accessToken;
	}
	
	/**
	 * To parse the AccessToken response and get access token value.
	 * 
	 * @param responseContent
	 * @return the access token value or null if not found.
	 */
	private static String parseAccessTokenResponse(String responseContent){
		
		String accessToken = null;
		
		// If there is access token in responseContent.
		final String ACCESS_TOKEN_EQUAL = "access_token=";
		if(responseContent.contains(ACCESS_TOKEN_EQUAL)){
			accessToken = responseContent.substring(responseContent.indexOf(ACCESS_TOKEN_EQUAL) + ACCESS_TOKEN_EQUAL.length());
		}
		
		return accessToken;
	}
	
	/**
	 * To build the ACCESS_TOKEN URL from the given CODE URL
	 * 
	 * @param codeUrl
	 * @return
	 */
	private static String buildAccessTokenUrlWithCodeUrl(String codeUrl){
		
		final String QUESTION_CODE_EQUAL = "?code=";
		
		String code = codeUrl.substring(codeUrl.indexOf(QUESTION_CODE_EQUAL) + QUESTION_CODE_EQUAL.length());
		Constant.ACCESS_TOKEN_URL = Constant.ACCESS_TOKEN_URL.replace(Constant.THE_CODE_FROM_ABOVE, code);
		
		return Constant.ACCESS_TOKEN_URL;
	}
}
